<?php
//生成文章主函数文件

/**
 * 生成文章类
 */
class WBPR {
    public $config;
    public $titles;
    public $contents;
    public $keywords;
    public $tags = array();

    public function __construct() {

        $is_hide_cat = wb_option('wb_pr_cathide');
        if ($is_hide_cat) {
            add_filter('pre_get_posts', array($this, 'hide_category'));
        }

        //$this->init();
        add_action("wp_ajax_wb_post_robot", array($this, 'init'), 10);

    }

    //搜索结果/首页排除某些分类的文章
    public function hide_category($query) {
        $cat = wb_option('wb_pr_cat', 0);
        if ($cat && !$query->is_admin && ($query->is_search || $query->is_home)) {
            $query->set('cat', -$cat);
        }
        return $query;
    }

    public function init() {
        if (!function_exists('wp_get_current_user')) {
            require ABSPATH . WPINC . '/pluggable.php';
        }

        if (!is_super_admin()) {
            $this->return_json('请登录后操作！');
        }

        $this->config = array_map('trim', array(
            'cat' => wb_option('wb_pr_cat'),
            'con_max' => wb_option('wb_pr_content_max', 200),
            'key_num' => wb_option('wb_pr_keyword_num', 2),
            'is_tag' => wb_option('wb_pr_keywordtotag', 0),
            'desc' => wb_option('wb_pr_desc', ''),
            'img' => wb_option('wb_pr_img'),
            'desc_con' => wb_option('wb_pr_desctocon'),
            'insert_char' => wb_option('wb_pr_char_off'),
            'esc_attr' => wb_option('wb_pr_esc_attr'),
            'iconv' => wb_option('wb_pr_iconv',1),
            'title_in_line' => wb_option('wb_pr_title_in_line', 0)
        ));
        $this->keywords = array_map('trim', explode("\n", wb_option('wb_pr_keywords', '')));

        if($this->config['title_in_line']){
            list($post_title,$post_content) = $this->get_content(true);
        }else{
            $post_title = $this->get_title();
            $post_content = $this->get_content();
        }

        //检查是否为空
        $this->check_empty($post_title, 'title');
        $this->check_empty($post_content, 'content');
        //$this->check_empty($this->keywords, 'keyword');

        // echo $this->get_title();
        // echo "\r\n";
        // echo $this->get_content();
        // echo "\r\n";
        // var_dump($this->tags);
        // 
        // time action
        $wb_pr_time_num = wb_option('wb_pr_time_num', 0);

        $time = wp_date('Y-m-d H:i:s', time() + rand(0, $wb_pr_time_num * 60));

        $post = array(
            'comment_status' => 'closed', // 评论的状态，'closed'关闭评论.
            'post_category' => array($this->config['cat']),
            'post_title' => $post_title, //文章标题，必填
            'post_content' => $post_content, //文章内容，必填
            'post_excerpt' => $this->config['desc'], //摘要信息
            'post_status' => 'publish', //['draft' | 'publish' | 'pending' | 'future' | 'private']//新文章的状态
            'post_date' => $time,
            'post_type' => 'post', //文章类型：文章、页面、链接、菜单、其他定制类型
            'tags_input' => implode(',', $this->tags), //标签字符串
        );

        $post_id = wp_insert_post($post);
        if ($post_id) {
            $url = get_permalink($post_id);
            $this->baidu_submit($url);
            $this->return_json('<a href="' . $url . '" target="_banlk">' . $post_title . '</a>', 1);
        }
        $this->return_json('系统错误');
    }

    //文章标题处理
    public function get_title() {
        $title = esc_attr(trim(rtrim($_FILES['file']['name'], '.txt')));
        $this->check_empty($title, '标题');
        return $title;
    }

    //文章内容处理
    //文章内容处理
    public function get_content($title_in_line = false) {

        if ($this->config['iconv']) {
            $ctxt = stream_context_create(array('file' => array('encoding' => 'gb2312')));
            $content = $this->autoiconv(trim(file_get_contents($_FILES['file']['tmp_name'], FILE_TEXT, $ctxt)));
        }else{
            $content = trim(file_get_contents($_FILES['file']['tmp_name'], FILE_TEXT));
        }

        if($title_in_line){
            $post_title = explode("\n",$content)[0];
            $content = trim(ltrim($content,$post_title));
//            $post_tag = '';
//            preg_match('/^(\w|-)+/i', $content, $match);
//            if($match[0]){
//                $post_tag = $match[0];
//            }
        }



        if ($this->config['esc_attr']) {
            $content = wpautop(esc_attr($content));
        } else {
            $content = wpautop($content);
        }

        $keyword_arr = $this->get_keyword();
        $content = $this->keywordInsert($content, $keyword_arr);

        $content = (empty($this->config['img'])) ? $content : "<img src=\"{$this->config['img']}\" class=\"aligncenter\"/>\r\n" . $content;
        //这里是摘要插入图片前面，如果需要放到图片后面就把后面整句搞到上面那句的上面
        $content = ($this->config['desc_con']) ? "<p>{$this->config['desc']}</p>\r\n" . $content : $content;
        if($title_in_line){
            return array($post_title,$content);
        }
        return $content;
    }


    //关键词插入到内容
    public function keywordInsert($txt, $insert) {
        preg_match_all("/[\x01-\x7f]|[\xe0-\xef][\x80-\xbf]{2}/", $txt, $match);

        $delay = array();
        $add = 0;
        foreach ($match[0] as $k => $v) {
            if ($v == '<') {
                $add = 1;
            }

            if ($add == 1) {
                $delay[] = $k;
            }

            if ($v == '>') {
                $add = 0;
            }
        }

        $str_arr = $match[0];
        $len = count($str_arr);

        foreach ($insert as $k => $v) {
            $insertk = $this->insertK($len - 1, $delay);
            $str_arr[$insertk] .= $insert[$k];
        }
        return join('', $str_arr);
    }

    public function insertK($count, $delay) {
        $insertk = rand(0, $count);
        if (in_array($insertk, $delay)) {
            $insertk = $this->insertK($count, $delay);
        }
        return $insertk;
    }

    //生成乱码
    public function getChar($num) {
        $arr = array();
        for ($a = 0; $a < $num; $a++) {
            $b = '';
            for ($i = 0; $i < 3; $i++) {
                $a = chr(mt_rand(0x00, 0xFF)) . chr(mt_rand(0x00, 0xFF));
                // 转码
                $b .= iconv('GB2312', 'UTF-8', $a);
            }
            $arr[] = $b;
        }

        return $arr;
    }

    //获取关键词数组
    public function get_keyword() {
        $tag_arr = array();
        if(count($this->keywords) < absint($this->config['key_num'])){
            return array();
        }
        $karr = array_rand($this->keywords, absint($this->config['key_num']));
        foreach ((array)$karr as $key) {
            if ($this->keywords[$key]) {
                $tag_arr[] = $this->keywords[$key];
            }
        }
        if ($this->config['is_tag']) {
            $this->tags = $tag_arr;
        }
        return $tag_arr;
    }

    //检查不得为空，为空返回提示
    public function check_empty($arr, $tip = '') {
        if (is_array($arr)) {
            foreach ($arr as $v) {
                if (!empty($v)) {
                    return;
                }
            }

        } elseif (is_string($arr)) {
            if (!empty($arr)) {
                return;
            }
        }

        $this->return_json($tip . '不得为空');
    }

    public function return_json($msg, $status = 0) {
        ob_clean();
        header('Content-type:text/json');
        if (!is_array($msg)) {
            $msg = $msg ? $msg : '操作成功';
        }
        echo json_encode(array(
            'status' => $status,
            'data' => $msg,
        ));
        die();
    }

    //百度推送
    public function baidu_submit($url) {
        $off = wb_option('wb_pr_bd_off');
        $token = wb_option('wb_pr_bd_token');
        if ($off && $token) {
            $urls[] = $url; //你的文章的具体网址,具体要根据自己的情况修改.这里是伪静态的形式
            $myurl = str_replace(array('/', 'https:', 'http:'), array('', '', ''), home_url());
            $api = 'http://data.zz.baidu.com/urls?site=' . $myurl . '&token=' . $token;
            $ch = curl_init();
            $options = array(
                CURLOPT_URL => $api,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => implode("\n", $urls),
                CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
            );
            curl_setopt_array($ch, $options);
            $result = curl_exec($ch);
        }
    }

    /*
    @params $str 输入字符 $type 所需获取编码
    @author 长行
     */
    public function autoiconv($str, $type = "utf-8") {

        $utf32_big_endian_bom = chr(0x00) . chr(0x00) . chr(0xfe) . chr(0xff);
        $utf32_little_endian_bom = chr(0xff) . chr(0xfe) . chr(0x00) . chr(0x00);
        $utf16_big_endian_bom = chr(0xfe) . chr(0xff);
        $utf16_little_endian_bom = chr(0xff) . chr(0xfe);
        $utf8_bom = chr(0xef) . chr(0xbb) . chr(0xbf);

        $first2 = substr($str, 0, 2);
        $first3 = substr($str, 0, 3);
        $first4 = substr($str, 0, 3);

        if ($first3 == $utf8_bom) {
            $icon = 'utf-8';
        } elseif ($first4 == $utf32_big_endian_bom) {
            $icon = 'utf-32be';
        } elseif ($first4 == $utf32_little_endian_bom) {
            $icon = 'utf-32le';
        } elseif ($first2 == $utf16_big_endian_bom) {
            $icon = 'utf-16be';
        } elseif ($first2 == $utf16_little_endian_bom) {
            $icon = 'utf-16le';
        } else {
            $icon = "GBK";
            //return $str;
        }
        return iconv($icon, $type, $str);
    }
}

new WBPR;